<?php


namespace app\common\services;


use think\Exception;
use think\facade\Config;
use think\facade\Env;

require_once Env::get('ROOT_PATH').'extend/aop/request/AlipayTradeAppPayRequest.php';
require_once Env::get('ROOT_PATH').'extend/aop/AopCertClient.php';

class AlipayService
{
    /**
     * 头条端-调用APP支付
     * @param $orderInfo
     * @param $topicInfo
     * @return \AlipayTradeAppPayRequest
     */
    public function getAppOrder($orderInfo,$topicInfo){
        writeLog('进入支付宝APP支付下单方法','支付调用信息');
        try{
            $aop = new \AopCertClient();
            $appCertPath = Config::get('params.alipay_appCertPath');
            $alipayCertPath = Config::get('params.alipay_alipayCertPath');
            $rootCertPath = Config::get('params.alipay_rootCertPath');
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = Config::get('params.alipay_app_id');
            $aop->rsaPrivateKey = Config::get('params.alipay_rsaPrivateKey');
            $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset = 'utf-8';
            $aop->format = 'json';
            $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
            $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
            $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号

            $request = new \AlipayTradeAppPayRequest ();
            $body = array();
            $body['out_trade_no'] = $orderInfo['out_order_no'];
            $body['subject'] = Config::get('params.tt_pay_order_subject');
            $body['total_amount'] = $orderInfo['total_amount'] / 100;
            $body['product_code'] = 'QUICK_MSECURITY_PAY';
            $body['goods_type'] = 0;
            $body['timeout_express'] = '30m';
            writeLog($body,'支付调用信息支付宝下单基础信息');
            $request->setBizContent(json_encode($body));
            $request->setNotifyUrl(Config::get('params.alipay_notify_url'));
            $result = $aop->sdkExecute($request);
            writeLog($result,'支付调用信息生成支付宝下单字符串');
            writeLog('退出支付宝APP支付下单方法','支付调用信息');
            return $result;
        }catch (\Exception $e){
            writeLog($e->getMessage(),'支付宝下单异常信息');
            throw new Exception('支付宝统一下单异常');
        }
    }
}